package com.lanyou.esb.cook.proxy.redis.proxy.impl;

import java.io.IOException;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.exceptions.JedisException;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.lanyou.esb.cook.proxy.common.Constants4Redis;
import com.lanyou.esb.cook.proxy.redis.JedisPoolUtils;
import com.lanyou.esb.cook.proxy.redis.proxy.base.BaseListJedisProxy;

/**
 * 接口平均响应时间键值Redis操作代理 <br>
 * 
 * @author Davey.wu
 */
public class IfAvgResTimesKeysJedisProxy extends BaseListJedisProxy<String> {

	public IfAvgResTimesKeysJedisProxy() {
		this.setKey(Constants4Redis.REDIS_LIST_KEY_IF_AVG_RES_TIMES);
	}

	/**
	 * 获取接口平均响应时间
	 * 
	 * @return
	 */
	public String get() {
		String result = "";
		Jedis jedis = JedisPoolUtils.getJedis();
		if (jedis == null) {
			return "";
		}
		boolean broken = false;
		try {
			result = jedis.lpop(this.getKey());
		} catch (Exception e) {
			broken = true;
		} finally {
			JedisPoolUtils.returnRes(jedis, broken);
		}
		return result;
	}

	/**
	 * 重新设置接口平均响应时间
	 * 
	 * @param value
	 *            ：值
	 * @throws JedisException
	 * @throws JsonParseException
	 * @throws JsonMappingException
	 * @throws IOException
	 */
	public void reset(String value) throws JedisException, JsonParseException,
			JsonMappingException, IOException {
		Jedis jedis = JedisPoolUtils.getJedis();
		if (jedis == null) {
			return;
		}
		boolean broken = false;
		try {
			jedis.lpush(this.getKey(), value);
		} catch (Exception e) {
			broken = true;
		} finally {
			JedisPoolUtils.returnRes(jedis, broken);
		}
	}

	/**
	 * 以字符串的方式加入
	 * 
	 * @param key
	 *            ：键
	 * @param value
	 *            ：值
	 * @throws JedisException
	 * @throws JsonProcessingException
	 */
	public void rpushAsStr(String key, String value) throws JedisException,
			JsonProcessingException {
		Jedis jedis = JedisPoolUtils.getJedis();
		if (jedis == null) {
			return;
		}
		boolean broken = false;
		try {
			jedis.rpush(key, value);
		} catch (Exception e) {
			broken = true;
		} finally {
			JedisPoolUtils.returnRes(jedis, broken);
		}
	}
}
